package com.xu.blog_after_end.service;

import com.xu.blog_after_end.NotFoundException;
import com.xu.blog_after_end.dao.TypeRepository;
import com.xu.blog_after_end.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeRepository typeRepository;
    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);  // 保存
    }
    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findById(id).orElse(null);  // 通过id获取
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);  // 分页查询
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();    // 获取所有分类
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        // 不再按照 "blogs.size" 排序，直接使用分页查询
        Pageable pageable = PageRequest.of(0, size);
        return typeRepository.findTop(pageable);  // 获取博客数量最多的前size个分类
    }



    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.findById(id).orElse(null);
        if(t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type, t);  // 将type中的数据拷贝到t中
        return typeRepository.save(t);  //更新
    }
    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }   // 通过名字获取分类
}
